<template>
  <el-scrollbar>
    <div class="company-info-form flex flex-col relative">
      <div class="absolute top-0 right-10">
        <EditSaveButton :isEdit="isEdit" @buttonClick="buttonClick" />
      </div>
      <div class="form-container mt-5">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="140px"
          :disabled="disabled"
        >
          <el-form-item label="公司logo" prop="logo">
            <MultiImageUpload v-model="formData.logo" :limit="1" :disabled="disabled" />
          </el-form-item>

          <el-form-item label="企业宣传" prop="indexImage">
            <MultiImageUpload v-model="formData.indexImage" :limit="10" :disabled="disabled" />
          </el-form-item>
          <el-form-item label="营业时间" prop="businessHoursStart" required :rules="rules">
            <el-time-select
              v-model="formData.businessHoursStart"
              style="width: 200px"
              :max-time="formData.businessHoursEnd"
              placeholder="开始时间"
              :picker-options="{ start: '00:00', step: '00:30', end: '24:00' }"
            />
            &nbsp;&nbsp;至&nbsp;&nbsp;
            <el-time-select
              v-model="formData.businessHoursEnd"
              style="width: 200px"
              :min-time="formData.businessHoursStart"
              placeholder="结束时间"
              :picker-options="{ start: '00:00', step: '00:30', end: '24:00' }"
            />
          </el-form-item>
          <el-form-item label="服务亮点" prop="introduce">
            <el-input
              v-model="formData.introduce"
              type="textarea"
              placeholder="请输入服务亮点"
              :maxlength="2000"
              show-word-limit
            ></el-input>
          </el-form-item>
          <el-form-item label="佣金比例" prop="introduce">
            {{ formData.mallCommission * 100 }}%
          </el-form-item>
          <!--          <el-form-item v-if="formData.materialCategory" label="经营品类">
            {{ formData.materialCategory }}
          </el-form-item>
          <el-form-item v-if="formData.manageBrand" label="品牌">
            {{ formData.manageBrand }}
          </el-form-item> -->

          <el-form-item
            v-for="item in props.dictCodes"
            :key="item.id"
            :label="item.name"
            :prop="item.fieldName"
          >
            <TagSelect
              v-if="item.type == 'tree'"
              :key="item.id"
              v-model="formData[item.fieldName]"
              :tag-list="item.dictDataList"
              :disabled="disabled"
            />
            <el-input
              v-else-if="item.type == 'input'"
              v-model="formData[item.fieldName]"
              placeholder="请输入"
              :disabled="disabled"
            />
            <div v-else-if="item.type == 'tag'" class="flex gap-2">
              <el-tag
                v-for="tag in formData[item.fieldName]"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleClose(tag, item.fieldName)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="InputRef"
                v-model="inputValue"
                class="w-20"
                size="small"
                @keyup.enter="handleInputConfirm(item.fieldName)"
                @blur="handleInputConfirm(item.fieldName)"
              />
              <el-button v-else class="button-new-tag" size="small" @click="showInput">
                + 新增
              </el-button>
            </div>
          </el-form-item>
          <!-- <el-form-item
            v-if="userType == SYSTEM_TYPE_REVERSE_OBJECT['家居建材'] && formData.categoryNames"
            label="经营范围"
            prop="manageRange"
          >
            <el-tag
              v-for="item in manageRangeList"
              :key="item"
              type="success"
              style="margin-right: 10px"
            >
              {{ item }}
            </el-tag>
          </el-form-item> -->
          <!-- <el-form-item label="所在商圈/商场" prop="mallName">
            <MallSelect :disabled="true" :defaultMall="defaultMall" />
          </el-form-item> -->
          <el-form-item label="门店地址" prop="storeAddress">
            <el-input v-model="formData.storeAddress" placeholder="请输入地址" disabled></el-input>
            <Map
              ref="mapContainer"
              class="map-container"
              :lat="formData.latitude"
              :lng="formData.longitude"
            ></Map>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </el-scrollbar>
</template>
<script setup>
import { SYSTEM_TYPE_REVERSE_OBJECT } from "@/utils/enums/system";
import { editCompanyIndex, getCompanyEnterInfo, getCompanyIndex } from "@/api/myIndex/index";
import TagSelect from "@/components/TagSelect/index.vue";
import Map from "@/components/Map/index.vue";
import { useCategory } from "@/hooks/useCategory";
const { getMaterialCategory, getSpecialLevelList } = useCategory();
import { useUserStore } from "@/store/modules/user";
import { storeGetUserType } from "@/utils/auth";
import { findPranctitionerMerchantCompanyVO } from "@/utils/common";
import { UserTypeEnum } from "@/enums/system/UserEnum";
import { MYINDEX_AUDIT_STATUS } from "@/views/hide/myIndex/enums/index.ts";
// import type { InputInstance } from "element-plus";

/**
 * 获取用户类型，看展示哪种主页
 */
const userType = computed(() => {
  let storeUserType = storeGetUserType();
  // 如果是从业人员，直接拿上级的公司type
  if (storeUserType === UserTypeEnum.PRACTITIONER.value) {
    return findPranctitionerMerchantCompanyVO().merchantUserType;
  }
  return storeUserType;
});
const userStore = useUserStore();
const userId = computed(() => userStore.userInfo.userId);

const props = defineProps({
  disabled: {
    type: Boolean,
    default: false,
  },
  dictCodes: {
    type: Array,
    default: () => [],
  },
});
const formData = ref({
  introduce: "", // 服务亮点
  storeAddress: "", // 地址
  logo: [], // 公司logo
  indexImage: [], // 主页图片
  manageRange: [], // 经营范围
  materialCategory: "",
  manageBrand: "",
  businessHoursStart: "",
  businessHoursEnd: "",
  mallName: "",
  mallCommission: 0,
});

/**
 *  所在商圈/商场 处理
 *
 */
const defaultMall = ref({
  mallNameId: "",
  mallName: "",
});

const rules = ref({
  businessHoursStart: [{ required: true, message: "请输入营业时间开始时间", trigger: "blur" }],
  businessHoursEnd: [{ required: true, message: "请输入营业时间结束时间", trigger: "blur" }],
});
const formRef = ref(null);
const inputVisible = ref(false);
// const InputRef = ref<InputInstance>();
const InputRef = ref(null);
const inputValue = ref();

function handleClose(tag, name) {
  formData.value[name].splice(formData.value[name].indexOf(tag), 1);
}

function showInput() {
  inputVisible.value = true;
  nextTick(() => {
    // InputRef.value!.input!.focus();
    InputRef.value.input.focus();
  });
}

function handleInputConfirm(name) {
  if (inputValue.value) {
    formData.value[name].push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
}

const manageRangeList = computed(() => {
  return formData.value.categoryNames;
});
// 控制按钮，是否可以进行编辑
const isEdit = ref(false);
const disabled = computed(() => {
  return isEdit.value ? false : true;
});
const buttonClick = () => {
  if (isEdit.value) {
    // 点击了保存按钮
    submitForm();
  } else {
    // 点击了编辑按钮
    isEdit.value = !isEdit.value;
  }
};
const submitForm = async () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid) => {
      if (valid) {
        //saveFormFunc();
        let params = {
          ...formData.value,
          businessHoursStart: formData.value.businessHoursStart
            ? formData.value.businessHoursStart + ":00"
            : "",
          businessHoursEnd: formData.value.businessHoursEnd
            ? formData.value.businessHoursEnd + ":00"
            : "",
          logo: JSON.stringify(
            formData.value.logo?.map((item) => {
              return {
                name: item.name,
                url: item.url,
              };
            }) || "[]"
          ),
          indexImage: JSON.stringify(
            formData.value.indexImage?.map((item) => {
              return {
                name: item.name,
                url: item.url,
              };
            }) || "[]"
          ),
        };
        props.dictCodes?.forEach((item) => {
          params[item.fieldName] = formData.value[item.fieldName].join(",");
        });
        if (formData.value.id) {
          params.id = formData.value.id;
        }
        try {
          await editCompanyIndex(params);
          ElMessage.success("保存成功");
          resolve(true);
          isEdit.value = !isEdit.value;
          getDefaultMessage();
        } catch (error) {
          console.error("保存失败", error);
          reject(false);
        }
        // 这里可以调用接口提交表单数据
      } else {
        console.error("表单验证失败");
        reject(false);
      }
    });
  });
};

const resetForm = () => {
  formRef.value.resetFields();
};
/**
 * 获取默认表单数据
 */
const getDefaultMessage = async () => {
  try {
    const res = await getCompanyIndex(userId.value);
    const data = res.data;

    if (!data) {
      return;
    }
    //formData.value = data;
    formData.value = {
      id: data.id,
      logo: JSON.parse(data.logo),
      indexImage: JSON.parse(data.indexImage),
      introduce: data.introduce,
      storeAddress: data.storeAddress,
      latitude: data.latitude,
      longitude: data.longitude,
      manageRange: data.manageRange,
      manageBrand: data.manageBrand,
      materialCategory: data.materialCategory,
      businessHoursStart: data.businessHoursStart ? data.businessHoursStart.substring(0, 5) : "",
      businessHoursEnd: data.businessHoursEnd ? data.businessHoursEnd.substring(0, 5) : "",
      mallName: data.mallName,
      mallCommission: data.mallCommission,
    };

    // 家居建材才有categoryNames
    if (userType.value == SYSTEM_TYPE_REVERSE_OBJECT["家居建材"]) {
      formData.value.categoryNames = data.categoryNames;
    }
    props.dictCodes.forEach((item) => {
      formData.value[item.fieldName] =
        (data[item.fieldName] && data[item.fieldName].split(",")) || [];
    });
    formRef.value?.clearValidate();
  } catch (error) {
    console.error("获取默认消息失败", error);
  }
};
const handleDymaticRules = async () => {
  // 动态生成规则
  let dymaticRules = {};
  props.dictCodes.forEach((item) => {
    if (item.type === "input") {
      dymaticRules[item.fieldName] = [
        { required: true, message: `请选择${item.name}`, trigger: "blur" },
      ];
    } else {
      dymaticRules[item.fieldName] = [
        { required: true, message: `请选择${item.name}`, trigger: ["change", "blur"] },
      ];
    }
  });
  rules.value = {
    introduce: [{ required: true, message: "请输入服务亮点", trigger: "blur" }],
    address: [{ required: true, message: "请输入地址", trigger: "blur" }],
    logo: [{ required: true, message: "请上传公司logo", trigger: "change" }],
    indexImage: [{ required: true, message: "请上传主页图片", trigger: "change" }],
    ...dymaticRules,
  };
};
const getDefaultFormFunc = async () => {
  try {
    const res = await getCompanyEnterInfo(userStore.userInfo.userId);
    const data = res.data;
    defaultMall.value = {
      mallNameId: data.mallNameId,
      mallName: data.mallName,
    };
  } catch (err) {
    console.log(err);
  }
};
const materialCategoryLevelList = ref([]);
onMounted(async () => {
  await getMaterialCategory();
  if (!formData.value.logo) {
    isEdit.value = true;
  }
  materialCategoryLevelList.value = getSpecialLevelList(2);
  getDefaultFormFunc();
  // 去掉了  关联 src/views/hide/myIndex/index.vue 中的逻辑
  handleDymaticRules();
  getDefaultMessage();
});
defineExpose({
  submitForm,
  resetForm,
  getDefaultMessage,
});
</script>
<style lang="scss" scoped>
.map-container {
  margin: 20px 0;
  width: 100%;
  height: 400px;
}
.company-info-form {
  height: 100%;
  overflow-y: auto;
  .form-container {
    width: 70%;
  }
}
</style>
